package com.dc.system.service.impl;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.model.BaseModel;
import com.dc.system.mapper.SysOrganMapper;
import com.dc.system.model.SysDept;
import com.dc.system.model.SysOrgan;
import com.dc.system.model.SysUser;
import com.dc.system.service.SysOrganService;
import com.dc.common.verification.RegexUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: SysOrganServiceImpl
 * @Author: ChenXueLi
 * @Date: 2018-05-05 10:38
 */
@Service
public class SysOrganServiceImpl implements SysOrganService {

    @Autowired
    private SysOrganMapper sysOrganMapper;

    /**
     * 添加一个单位
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel addSysOrgan(SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        // 验证数据的完整性
        // 保证上级部门id存在除非不设置上级部门
        if(sysOrgan.getFk_parent_id() != 0) {
            // 查询出是否存在该部门
            boolean hasOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getFk_parent_id()) != null;
            if(!hasOrgan) {
                throw new BusinessException(-102, "上级单位查询失败");
            }
        }
        if(sysOrgan.getContact() == null || "".equals(sysOrgan.getContact())) {
            throw new BusinessException(-103, "联系人不能为空");
        }
        if(sysOrgan.getContact_phone() == null || !RegexUtil.isPhone(sysOrgan.getContact_phone())) {
            throw new BusinessException(-104, "联系人电话不能为空");
        }
        if(sysOrgan.getAddress() == null || "".equals(sysOrgan.getAddress())) {
            throw new BusinessException(-105, "地址不能为空");
        }
        if(sysOrgan.getNature() == null || "".equals(sysOrgan.getNature())) {
            throw new BusinessException(-106, "单位性质不能为空");
        }
        if(sysOrgan.getTelephone() == null || !RegexUtil.isPhone(sysOrgan.getTelephone())) {
            throw new BusinessException(-107, "座机不能为空");
        }
        // 传真可以不填写
        if(sysOrgan.getFax() != null && !RegexUtil.match(sysOrgan.getFax(), "/^(\\d{3,4}-)?\\d{7,8}$/")) {
            throw new BusinessException(-108, "传真格式不正确");
        }
        // 排序
        // 查询当前的数总数
        int currentRows = sysOrganMapper.getSysOrgansCount();
        // 当前排序号是在总数之后或者为0的情况下是在末尾直接追加
        if(sysOrgan.getOrder_code() > currentRows || sysOrgan.getOrder_code() == 0) {
            // 排在末尾
            sysOrgan.setOrder_code(currentRows + 1);
        }else {
            // 重新校验排序
            int tempEffectRows = sysOrganMapper.updateSysOrganOrderCodeIncreaseByOrderCode(sysOrgan);
        }

        // 设置默认数据
        sysOrgan.setCreate_time(new Date());
        sysOrgan.setCreate_user_name(sysUser.getAccount());
        sysOrgan.setCreate_user_id(sysUser.getUser_id());
        sysOrgan.setUpdate_time(new Date());
        sysOrgan.setUpdate_user_name(sysUser.getAccount());
        sysOrgan.setUpdate_user_id(sysUser.getUser_id());
        sysOrgan.setIs_deleted(1);
        sysOrgan.setVersion(0);

        int effectRows = sysOrganMapper.addSysOrgan(sysOrgan);
        if(effectRows != 1) {
            sysOrganMapper.updateSysOrganOrderCodeDecreaseByOrderCode(sysOrgan);
            throw new BusinessException(-109, "系统错误，添加单位失败！");
        }
        baseModel.setCode(0);
        baseModel.setMessage("添加单位成功");
        // 更新数据
        sysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id());
        baseModel.setData(sysOrgan);
        return baseModel;
    }

    /**
     * 根据单位id删除一个单位
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel deleteSysOrganById(SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }

        sysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id());
        if(sysOrgan == null) {
            throw new BusinessException(-102, "获取单位失败！");
        }
        sysOrgan.setUpdate_time(new Date());
        sysOrgan.setUpdate_user_name(sysUser.getAccount());
        sysOrgan.setUpdate_user_id(sysUser.getUser_id());
        sysOrgan.setIs_deleted(0);
        int effectRows = sysOrganMapper.deleteSysOrganById(sysOrgan);
        if(effectRows != 1) {
            throw new BusinessException(-103, "系统错误，删除单位失败！");
        }

        // 重整之后序号的单位
        effectRows = sysOrganMapper.updateSysOrganOrderCodeDecreaseByOrderCode(sysOrgan);

        baseModel.setCode(0);
        baseModel.setMessage("删除单位成功");
        baseModel.setData(sysOrgan);
        return baseModel;
    }

    /**
     * 根据单位id修改一个单位的信息
     * @param sysOrgan
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel updateSysOrganById(SysOrgan sysOrgan, BaseModel baseModel, HttpServletRequest request) throws Exception {
        // 获取用户
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        if(sysOrgan.getOrgan_id() == sysOrgan.getFk_parent_id()) {
            throw new BusinessException(-102, "上级单位不能是自身");
        }
        // 获取到原来的部门数据判断排序是否有变化
        SysOrgan originalSysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id());
        if(originalSysOrgan == null) {
            throw new BusinessException(-103, "获取单位id失败！");
        }
        // 验证数据的完整性
        // 保证上级部门id存在除非不设置上级部门
        if(sysOrgan.getFk_parent_id() != 0) {
            // 查询出是否存在该部门
            boolean hasOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getFk_parent_id()) != null;
            if(!hasOrgan) {
                throw new BusinessException(-104, "上级单位查询失败");
            }
        }
        if(sysOrgan.getContact() == null || "".equals(sysOrgan.getContact())) {
            throw new BusinessException(-105, "联系人不能为空");
        }
        if(sysOrgan.getContact_phone() == null || !RegexUtil.isTel(sysOrgan.getContact_phone())) {
            throw new BusinessException(-106, "联系人电话不能为空");
        }
        if(sysOrgan.getAddress() == null || "".equals(sysOrgan.getAddress())) {
            throw new BusinessException(-107, "地址不能为空");
        }
        if(sysOrgan.getNature() == null || "".equals(sysOrgan.getNature())) {
            throw new BusinessException(-108, "单位性质不能为空");
        }
        if(sysOrgan.getTelephone() == null || !RegexUtil.isPhone(sysOrgan.getTelephone())) {
            throw new BusinessException(-109, "座机不能为空");
        }
        // 传真可以不填写
        if(sysOrgan.getFax() != null && !RegexUtil.match(sysOrgan.getFax(), "/^(\\d{3,4}-)?\\d{7,8}$/")) {
            throw new BusinessException(-110, "传真格式不正确");
        }

        // 重新排序
        if(originalSysOrgan.getOrder_code() != sysOrgan.getOrder_code()) {
            // 先将原数据的执行减1
            int tempEffectRows = sysOrganMapper.updateSysOrganOrderCodeDecreaseByOrderCode(originalSysOrgan);
            // 再将新数据的加1
            tempEffectRows = sysOrganMapper.updateSysOrganOrderCodeIncreaseByOrderCode(sysOrgan);
        }

        sysOrgan.setUpdate_time(new Date());
        sysOrgan.setUpdate_user_name(sysUser.getAccount());
        sysOrgan.setUpdate_user_id(sysUser.getUser_id());
        sysOrgan.setVersion(originalSysOrgan.getVersion());

        int effectRows = sysOrganMapper.updateSysOrganById(sysOrgan);
        if(effectRows != 1) {
            sysOrganMapper.updateSysOrganOrderCodeDecreaseByOrderCode(sysOrgan);
            sysOrganMapper.updateSysOrganOrderCodeIncreaseByOrderCode(originalSysOrgan);
            throw new BusinessException(-111, "系统错误，修改单位失败！");
        }
        baseModel.setCode(0);
        baseModel.setMessage("修改单位成功");
        // 更新部门数据
        sysOrgan = sysOrganMapper.getSysOrganById(sysOrgan.getOrgan_id());
        baseModel.setData(sysOrgan);
        return baseModel;
    }

    /**
     * 分页查询所有单位
     * @param pageInfo
     * @param sysOrgan
     * @param sysDept
     * @param baseModel
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public BaseModel getSysOrgans(PageInfo<?> pageInfo, SysOrgan sysOrgan, SysDept sysDept, BaseModel baseModel, HttpServletRequest request) throws Exception {
        SysUser sysUser = (SysUser)request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        if(sysUser == null) {
            throw new BusinessException(-101, "用户获取失败");
        }
        Map<String, Object> params = new HashMap<>();
        // 添加参数
        if(sysOrgan.getName() != null && !"".equals(sysOrgan.getName())) {
            params.put("name", sysOrgan.getName());
        }
        if(sysOrgan.getFk_parent_id() != 0 && !"".equals(sysOrgan.getFk_parent_id())) {
            params.put("fk_parent_id", sysOrgan.getFk_parent_id());
        }
        if(sysOrgan.getContact() != null && !"".equals(sysOrgan.getContact())) {
            params.put("contact", sysOrgan.getContact());
        }
        if(sysOrgan.getContact_phone() != null && !"".equals(sysOrgan.getContact_phone())) {
            params.put("contact_phone", sysOrgan.getContact_phone());
        }
        if(sysOrgan.getStaff_num() != 0 && !"".equals(sysOrgan.getStaff_num())) {
            params.put("staff_num", sysOrgan.getStaff_num());
        }
        if(sysOrgan.getNature() != null && !"".equals(sysOrgan.getNature())) {
            params.put("nature", sysOrgan.getNature());
        }
        if(sysOrgan.getTelephone() != null && !"".equals(sysOrgan.getTelephone())) {
            params.put("telephone", sysOrgan.getTelephone());
        }
        if(sysOrgan.getFax() != null && !"".equals(sysOrgan.getFax())) {
            params.put("fax", sysOrgan.getFax());
        }
        if(sysOrgan.getOrder_code() != 0 && !"".equals(sysOrgan.getOrder_code())) {
            params.put("order_code", sysOrgan.getOrder_code());
        }
        if(sysOrgan.getAddress() != null && !"".equals(sysOrgan.getAddress())) {
            params.put("address", sysOrgan.getAddress());
        }
        if(sysOrgan.getMemo() != null && !"".equals(sysOrgan.getMemo())) {
            params.put("memo", sysOrgan.getMemo());
        }
        if(sysOrgan.getCreate_user_id() != 0 && !"".equals(sysOrgan.getCreate_user_id())) {
            params.put("create_user_id", sysOrgan.getCreate_user_id());
        }
        if(sysOrgan.getCreate_user_name() != null && !"".equals(sysOrgan.getCreate_user_name())) {
            params.put("create_user_name", sysOrgan.getCreate_user_name());
        }
        if(sysOrgan.getUpdate_user_id() != 0 && !"".equals(sysOrgan.getUpdate_user_id())) {
            params.put("update_user_id", sysOrgan.getUpdate_user_id());
        }
        if(sysOrgan.getUpdate_user_name() != null && !"".equals(sysOrgan.getUpdate_user_name())) {
            params.put("update_user_name", sysOrgan.getUpdate_user_name());
        }
        // 创建时间开始
        String create_time_start = request.getParameter("create_time_start");
        if(create_time_start != null && !"".equals(create_time_start)) {
            params.put("create_time_start", create_time_start);
        }
        // 创建时间结束
        String create_time_end = request.getParameter("create_time_end");
        if(create_time_end != null && !"".equals(create_time_end)) {
            params.put("create_time_end", create_time_end);
        }
        // 修改时间开始
        String update_time_start = request.getParameter("update_time_start");
        if(update_time_start != null && !"".equals(update_time_start)) {
            params.put("update_time_start", update_time_start);
        }
        // 修改时间结束
        String update_time_end = request.getParameter("update_time_end");
        if(update_time_end != null && !"".equals(update_time_end)) {
            params.put("update_time_end", update_time_end);
        }
        // 添加部门信息
        if(sysDept.getDept_id() != 0 && !"".equals(sysDept.getDept_id())) {
            params.put("deptId", sysDept.getDept_id());
        }
        // 判断是否需要分页查询（默认为分页查询）
        String getByPage = request.getParameter("getByPage");
        if(getByPage != null && !"".equals(getByPage)) {
            // 只要有值就不是分页查询
            List<SysOrgan> sysOrgans = sysOrganMapper.getSysOrgans(params);
            baseModel.setData(sysOrgans);
            baseModel.setMessage("查询成功");
        }else {
            int pageNum = pageInfo.getPageNum() <= 0 ? 0 : pageInfo.getPageNum();
            int pageSize = pageInfo.getPageSize() <= 0 ? 10 : pageInfo.getPageSize();
            // 分页插件,但是PageHelper必须在查询语句前，最好写在service实现层
            PageHelper.startPage(pageNum, pageSize);
            List<SysOrgan> sysOrgans = sysOrganMapper.getSysOrgans(params);
            // 通过pageHelper插件pageInfo封装，更加方便
            PageInfo<SysOrgan> resultSysOrgan = new PageInfo<SysOrgan>(sysOrgans);
            baseModel.setData(resultSysOrgan);
            baseModel.setMessage("查询成功");
        }
        return baseModel;
    }

}
